package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.pojo.Goods;
import org.example.service.GoodService;
import org.example.util.ResultMap;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 *@ClassName: GoodsController
 *@Author: CJ
 *@Date: 2021-9-5 15:52
 */
@Controller
@RequestMapping(path = "/goods")
@Api(tags = "商品管理相关接口")
@Slf4j
public class GoodsController {

    @Autowired
    private GoodService goodService;

    @GetMapping(path = "/selectOne")
    @ResponseBody
    @ApiOperation(value = "查询商品接口")
    @ApiImplicitParam(name = "id", value = "商品id", required = true)
    public ResultMap selectOne(@RequestParam(name = "id", defaultValue = "3") Long goodsid) {
        Goods goods = goodService.selectOneGoods(goodsid);
        log.info("查询到的商品数据：" + goods.toString());
        if (StringUtils.isEmpty(goods)) {
            return new ResultMap().fail().message("查询失败，没有您要的数据");
        }
        return new ResultMap().success().message("查询成功").data(goods);
    }

    @PostMapping(path = "/addGoods")
    @ResponseBody
    @ApiOperation(value = "添加商品的接口")
    public ResultMap addGoods(@Valid Goods goods, @NotNull BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            String defaultMessage = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
            return new ResultMap().fail().message(defaultMessage);
        }
        int i = goodService.addGoods(goods);
        if (i > 0) {
            return new ResultMap().success().message("添加成功");
        }
        return new ResultMap().fail().message("添加失败");
    }
}
